/*
 * @Author: sean
 * @Date:   2019-12-26 11:04:13
 * @Last Modified by:   sean
 * @Last Modified time: 2020-07-04 11:41:20
 */
import Vue from 'vue';

import utils from '../util';

import popups from './popups.js';

import Modal from './extend/Modal.vue';

/**
 * <p  v-popup.role="description" data-value="description" action="">新建</p>
 *
 * v-popup.<绑定的模态框>="<需要传入的值>"
 * data-value="<回调改变的值>"
 * data-title="设置标题"
 *
 * 添加 affirm 方法
 * @param  {[type]} option [description]
 * @return {[type]}        [description]
 */
let directives = {
  /**
   * 数据池
   * @type {Array}
   */
  store: {},
  /**
   * 弹出层
   * @type {Object}
   */
  popup: {
    bind: function (el, binding, vnode) {

    },
    inserted: function (el, binding, vnode) {
      let keys = vnode.elm.id || el.dataset.id || binding.expression || '_';
      let action = el.getAttribute('action') || '';
      directives.store[keys] = binding.value ? binding.value : [];
      utils.add_event(el, 'click', () => {
        // 获取双向绑定数据
        let value = directives.store[keys];
        // 获取对应模型
        let popup = utils.get_shift(binding.modifiers);
        // 获取窗口标题
        let title = el.dataset.title ? el.dataset.title : '操作窗口';
        // 绑定数据
        let vmodel = el.dataset.value ? el.dataset.value : '';
        // 设置宽度
        let width = el.dataset.width || 730;
        // VM实例
        let vm = vnode.context;

        // 判断模态框是否存在
        if (popups[popup]) {
          let visible = true;

          let content = Vue.extend(popups[popup].default);

          let instance = utils.get_instance(Vue.extend(Modal), {
            visible: visible,
            value: value,
            title: title,
            width: width,
            content: content
          });

          let model = document.body.appendChild(instance.$el);
          // 监听并移除节点
          instance.$watch('visible', res => {
            if (vmodel) {
              vm[vmodel] = instance.value;
            }
            instance.visible = false;
            document.body.removeChild(model);
            // 如果回调事件存在责执行
            if (vm[action]) {
              vm[action].apply(vm, [instance.value]);
            }
            if (vm.reload) {
              vm.reload();
            }
          });
        } else {
          console.log(popup + '模态框不存在');
        }
      });
      // console.log("查看绑定", [el, binding, vnode, directives.store]);
    },
    update: function (el, binding, vnode) {
      let keys = binding.expression ? binding.expression : '_';
      if (!utils.empty(binding.value)) {
        directives.store[keys] = binding.value;
      }
    }
  }

};

export default directives;
